﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dropit.BlogPageProvider.Blog;

namespace Dropit.BlogPageProvider.WordPress
{
	public class Post : IPost
	{
		public static List<Post> List(JoeBlogs.WordPressWrapper wrapper, WordPressId id)
		{
			try
			{
				return wrapper.GetRecentPosts(1000).Select<JoeBlogs.Structs.Post, Post>(post => new Post()
				{
					WordPressId = new WordPressId()
					{
						BlogId = id.BlogId,
						PostId = post.postid
					},
					Heading = post.title,
					Content = post.description,
					Created = post.dateCreated,
					Category = post.categories.ToList()
				})
				.ToList();
			}
			catch (Exception ex)
			{
			}
			return new List<Post>();
		}

		public static Post Load(JoeBlogs.WordPressWrapper wrapper, WordPressId id)
		{
			return List(wrapper, id).First(post => post.WordPressId.PostId == id.PostId);
		}

		public static Post SaveNew(JoeBlogs.WordPressWrapper wrapper, WordPressId parentId, IPost post)
		{
			JoeBlogs.Structs.Post wpPost = new JoeBlogs.Structs.Post();
			wpPost.title = post.Heading;
			wpPost.description = post.Content;
			wpPost.dateCreated = DateTime.UtcNow;
			wpPost.categories = post.Category.ToArray();
			parentId.PostId = wrapper.NewPost(wpPost, true);
			return Load(wrapper, parentId);
		}

		public WordPressId WordPressId { get; set; }

		#region IPost Members

		public string Id { get { return WordPressId.ToString(); } }
		public string Heading { get; set; }
		public string Content { get; set; }
		public DateTime Created { get; set; }
		public List<string> Category { get; set; }

		#endregion
	}
}